import React from 'react';
import ImageLazy from '../components/commons/ImageLazy';
import { connect } from 'react-redux'
const loading_img = require('!url?limit=8192&name=static/img/[hash:6].[ext]!../static/img/loading.png');
import {testApiUrl} from '../actions/index';

function GetQueryString(name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if (r != null)
                return unescape(r[2]);
            return null;
        }

        function addcookie(name,value,expireHours){
            var cookieString=name+"="+escape(value)+"; path=/";
            //判断是否设置过期时间
            if(expireHours>0){
                var date=new Date();
                date.setTime(date.getTime+expireHours*3600*1000);
                cookieString=cookieString+"; expire="+date.toGMTString();
            }
            document.cookie=cookieString;
        }

        function getcookie(name){
            var strcookie=document.cookie;
            var arrcookie=strcookie.split("; ");
            for(var i=0;i<arrcookie.length;i++){
                var arr=arrcookie[i].split("=");
                if(arr[0]==name)return decodeURIComponent(arr[1]); //增加对特殊字符的解析
            }
            return "";
        }

        function delCookie(name){//删除cookie
            var exp = new Date();
            exp.setTime(exp.getTime() - 1);
            var cval=getcookie(name);
            if(cval!=null) document.cookie= name + "="+cval+"; path=/;expires="+exp.toGMTString();
        }

let myDefault = React.createClass({
  componentWillMount:function(){
    const script1 = document.createElement("script");
    script1.src = "https://res.wx.qq.com/open/js/jweixin-1.0.0.js";
    script1.type = "text/javascript";
    script1.async = true;
    document.head.appendChild(script1);

    $('body').on('touchstart MSPointerDown pointerdown','a',function(){
      $(this).addClass('a_mouseDown')
    }).on('touchend MSPointerUp pointerup','a',function(){
      $(this).removeClass('a_mouseDown')
    })
  },
  componentDidMount:function(){
    var wxopenid = getcookie('wxopenid');
    var access_code = GetQueryString('code');
    if(wxopenid == "" || wxopenid == undefined){
        //alert(1);
        if(access_code == null){

            var fromurl = encodeURIComponent(location.href);
            //alert(fromurl);
            var url='https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx22ae3075d64a4f81&redirect_uri='+fromurl+'&response_type=code&scope=snsapi_base&state=STATE%23wechat_redirect&connect_redirect=1#wechat_redirect';
            window.location.href=url;
        }else {
            //alert(3);
            $.ajax({
                type:'get',
                url:testApiUrl + '/wxcs/service/oauth2_access_token',
                async:false,
                cache:false,
                data:{code:access_code},
                dataType:'jsonp',
                jsonp: 'jsonpCallback',
                jsonpCallback:'success_jsonpCallback',
                success:function(result){
                    // alert("access_token: "+result);
                    //alert(result.openid);
                    if (result!=null){
                        //alert(result);
                        addcookie('wxopenid',result.openid,360000);


                    }else {
                        console.log('微信身份识别失败 \n '+result);
                        location.href=fromurl;
                    }
                },
                error:function(XMLHttpRequest, textStatus, errorThrown) {
                       console.log(XMLHttpRequest.status);
                       console.log(XMLHttpRequest.readyState);
                       console.log(textStatus);
                }
            });
        }
    }
  },
  render:function(){
    return(
      <div id="loading" style={{'display':this.props.loading?'flex':'none'}}>
        <span><img src={loading_img} style={{width:".46rem"}} /></span>
      </div>
    )
  }
})

const mapStateToProps = (state)=>{
  let {loading} = state.app;
  return{
    loading:loading,
  }
}

export default connect(mapStateToProps)(myDefault);
